package com.common.base.http.exceptions

import android.os.Handler
import android.os.Looper
import com.common.base.tools.utils.logger

/**
 * Created by zsf on 2022/8/18 16:49
 * *******************
 * 全局异常拦截器
 * *******************
 */
class CrashHandler private constructor() : Thread.UncaughtExceptionHandler {
    /**
     * init 创建
     */
    fun init() {
        Thread.setDefaultUncaughtExceptionHandler(this)
        // 主线程的尝试性质的crash抓取
        Handler(Looper.getMainLooper()).post {
            //主线程异常拦截
            while (true) {
                try {
                    // 由于主线程的Crash是统一出现在loop()的case
                    Looper.loop() //主线程的异常会从这里抛出
                } catch (throwable: Throwable) {
                    logger.error("异常捕获", throwable)
                }
            }
        }
    }

    override fun uncaughtException(thread: Thread, throwable: Throwable) {
        try {
            logger.error("异常捕获", throwable)
            throwable.printStackTrace()
            thread.interrupt()
        } catch (ignored: Exception) {
        }
    }

    companion object {
        /**
         * CrashHandler实例的对 象
         */
        val instance = CrashHandler()
    }
}